package com.sq.News.controller;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.mysql.cj.Session;
import com.sq.News.pojo.NewsInfo;
import com.sq.News.pojo.RequestInfo;
import com.sq.News.service.NewsService;

@Controller

public class NewsController {
	@Autowired
	private NewsService newsService;
	@Autowired
	private RequestInfo requestInfo;

	public Session getSession() {
		return null;
	}

	@RequestMapping(value = "addNews")
	public String addNewsHtml() {
		return "add";
	}

	// 进入新闻网站首页
	@RequestMapping(value = "/news")
	public ModelAndView getModelAndView() {
		ModelAndView mv = null;
		try {
			mv = new ModelAndView("index");
			ArrayList<NewsInfo> news = newsService.getAllNews();
			mv.addObject("data", news);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mv;
	}

	// 向数据库添加记录
	@RequestMapping("/add1")
	public String addData(NewsInfo ni) {
		boolean isDone = false;
		isDone = newsService.addNews(ni);
		if (isDone) {
			return "done";
		} else {
			return "failed";
		}
	}

	// 根据新闻id删除数据库中的某个记录
	@RequestMapping("/deleteNews")
	@ResponseBody
	public String deleteData(HttpServletRequest request, String id) {
		System.out.println(id);
		boolean isDone = false;
		// isDone = newsService.deleteNews(Integer.parseInt(id));
		isDone = true;
		if (isDone) {
			requestInfo.setMessage("200");
			requestInfo.setMessage("删除成功");
			return new Gson().toJson(requestInfo);
		} else {
			requestInfo.setMessage("101");
			requestInfo.setMessage("删除失败");
			return new Gson().toJson(requestInfo);
		}
	}

	// 根据新闻id更新数据库中的记录
	@RequestMapping("/update1")
	public String updateData(NewsInfo ni) {
		boolean isDone = false;
		isDone = newsService.updateNews(ni);
		if (isDone) {
			return "done";
		} else {
			return "failed";
		}
	}

	// 点击某个新闻的链接后根据id获得该条新闻的内容等
	@RequestMapping("/read")
	public ModelAndView getContent(int id) {
		ModelAndView mv = null;

		try {
			mv = new ModelAndView("content");
			NewsInfo news = newsService.getContent(id);
			mv.addObject("data", news);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mv;
	}
}
